package com.intct.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gufg
 * @since 2025-08-19 16:33
 */
public class JDBCUtil {

    public static Connection getJDBCConnect() {
        String url = "jdbc:mysql://cdh-node:13306/travel_config";
        String username = "root";
        String password = "Test_090110";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> getQuery(Connection connection, String sql, Class<T> clazz) throws Exception {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();

        // 表元数据
        ResultSetMetaData metaData = resultSet.getMetaData();

        // 返回数据集
        List<T> objList = new ArrayList<>();

        while (resultSet.next()) {
            // Java反射，创建对象
            T obj = clazz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 值
                Object value = resultSet.getObject(i);

                // 将数据库中的蛇形命名转为小驼峰命名
                String colNmae = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                // Commons3包类
                BeanUtils.setProperty(obj, colNmae, value);
            }
            objList.add(obj);
        }
        return objList;
    }
}
